package com.cx.blog;


import com.cx.utils.util.JarUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

public class SqlGenerator {
    //-1小写,1大写
    public static final int format = -1;
    /**
     * 用来存储Java等属性类型与sql中属性类型的对照
     * </br>
     * 例如：java.lang.Integer 对应 integer
     */
    public static Map<String, String> map = new HashMap<>();

    static {
        map.put("boolean", "tinyint(1)");
        map.put("int", "int");
        map.put("short", "int");
        map.put("long", "bigint");
        map.put("float", "float");
        map.put("double", "double");
        map.put("char", "varchar(255)");
        map.put("java.lang.String", "varchar(255)");
        map.put("java.lang.Integer", "int");
        map.put("java.lang.byte[]", "blob");
        map.put("java.lang.Boolean", "bit");
        map.put("java.lang.Long", "bigint unsigned");
        map.put("java.math.BigInteger", "bigint unsigned");
        map.put("java.lang.Float", "float");
        map.put("java.lang.Double", "float");
        map.put("java.sql.Date", "datetime");
        map.put("java.sql.Time", "time");
        map.put("java.sql.Timestamp", "datetime");
        map.put("java.util.Date", "datetime");
        map.put("java.lang.Byte", "tinyint");
    }

    public static void main(String[] args) {
        sqlConstruction("G:\\chenxin\\codeWorkSpace\\trade-business-project\\trade-business-engine\\src\\main\\resources\\sql\\business.sql",
                "com.cx.blog.entity", true);
    }

    /**
     * 功能描述: 生成sql文件
     *
     * @param sqlFilePath     sql文件存储地址 如：G:\chenxin\codeWorkSpace\trade-business-project\trade-business-engine\src\main\resources\sql\business.sql
     * @param packagePathName 需要生成sql的类文件包名 如：com.cx.blog.entity
     * @param recursive       是否递归查询包下面的类
     * @author: chenxin
     * @date: 2022/8/17
     */
    public static void sqlConstruction(String sqlFilePath, String packagePathName, boolean recursive) {
        //生成sql的文件夹

        Set<Class<?>> classes;
        //获取包下的所有类名称
        try {
            classes = JarUtil.getClasses(packagePathName, recursive);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        StringBuilder sqlBuilder = new StringBuilder();
        for (Class<?> cls : classes) {
            String sql = generateSql(cls);
            sqlBuilder.append(sql);
        }

        StringToSql(sqlBuilder.toString(), sqlFilePath);
    }

    /**
     * 根据实体类生成建表语句
     *
     * @return
     */
    public static String generateSql(Class<?> clz) {
        try {
            String className = clz.getSimpleName();
            // 表表名adminUser → tb_admin_user
            className = getStandardFields(className).toLowerCase();
            Field[] fields = clz.getDeclaredFields();
            StringBuffer column = new StringBuffer();
            String varchar = " CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,";
            for (Field f : fields) {
                System.out.println(f.getType().getName());
                String typeName = f.getType().getName();
                if (f.getName().equals("serialVersionUID")) {
                    continue;
                }
                if ("java.lang.String".equals(typeName)) {
                    column.append(" \n `" + getStandardFields(f.getName()) + "`" + " " + map.get(typeName)).append(varchar);
                } else {
                    if (f.getName().equalsIgnoreCase("id")) {
                        column.append(" \n `id` bigint(20) NOT NULL AUTO_INCREMENT,");
                    } else {
                        column.append(" \n `" + getStandardFields(f.getName()) + "`" + " " + map.get(typeName)).append(",");
                    }
                }
            }
            StringBuffer sql = new StringBuffer();
            sql.append("\n DROP TABLE IF EXISTS `" + className + "`; ")
                    .append(" \n CREATE TABLE `" + className + "`  (")
//                    .append(" \n `id` int(11) NOT NULL AUTO_INCREMENT,")
                    .append(column)
                    .append(" \n PRIMARY KEY (`id`) USING BTREE,")
                    .append("\n INDEX `id`(`id`) USING BTREE")
                    .append(" \n ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;\n");
            return sql.toString();
        } catch (Exception e) {
//            log.info("该类未找到！");
            return null;
        }

    }

    /**
     * 转换为标准等sql字段 例如 adminUser → admin_user
     *
     * @param str 转换为字符串的字段名
     * @return
     */
    public static String getStandardFields(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (i != 0 && (c > 'A' && c < 'Z')) {
                sb.append("_");
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 将生成等String字符串 写进sql文件
     *
     * @param str  String字符串
     * @param path sql文件路径路径
     */
    public static void StringToSql(String str, String path) {
        if (format < 0) {
            str = str.toLowerCase();
        } else {
            str = str.toUpperCase();
        }
        System.out.println(str);
        byte[] sourceByte = str.getBytes();
        FileOutputStream os = null;
        try {
            //文件路径（路径+文件名）
            File file = new File(path);
            //文件不存在则创建文件，先创建目录
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            //文件输出流用于将数据写入文件
            os = new FileOutputStream(file);
            os.write(sourceByte);
            os.flush();
            System.out.println("生成成功!!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭文件输出流
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}